package com.changzhi.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.changzhi.common.constans.Constants;
import com.changzhi.common.constans.RedisConstans;
import com.changzhi.common.enums.ActivityPrizeEnum;
import com.changzhi.common.enums.MatchRoleEnum;
import com.changzhi.common.exception.ServiceException;
import com.changzhi.common.util.DateUtil;
import com.changzhi.ldyl.model.*;
import com.changzhi.ldyl.model.dto.MatchDto;
import com.changzhi.ldyl.model.dto.MemberDto;
import com.changzhi.ldyl.model.vo.MatchVo;
import com.changzhi.mapper.ActivityMatchMapper;
import com.changzhi.mapper.ActivityTeamMapper;
import com.changzhi.mapper.ActivityTeamMemberMapper;
import com.changzhi.mapper.UserSettingMapper;
import com.changzhi.service.ActivityService;
import com.changzhi.service.GiftService;
import com.changzhi.service.MatchService;
import com.changzhi.service.UserService;
import com.changzhi.util.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description:
 * @author: 小落
 * @date: 2021年07月21日
 */
@Slf4j
@Service
public class MatchServiceImpl implements MatchService {

	public final static Integer ACTIVITY_ID = 28;
	@Resource
	private ActivityTeamMapper activityTeamMapper;
	@Resource
	private UserService userService;
	@Resource
	private ActivityTeamMemberMapper activityTeamMemberMapper;
	@Resource
	private UserSettingMapper userSettingMapper;
	@Autowired
	private ActivityService activityService;
	@Autowired
	private RedisUtil redisUtil;
	@Autowired
	private GiftService giftService;
	@Resource
	private ActivityMatchMapper activityMatchMapper;
	public static Map<String, LocalDateTime> TIME_MAP = new HashMap<>();
	@Value("${spring.profiles.active}")
	private String env;

	@PostConstruct
	public void init(){
		redisUtil.del(RedisConstans.ACTIVITY + ACTIVITY_ID);
		Activity activity = activityService.getActivity(ACTIVITY_ID);
		//存活动时间
		TIME_MAP.put("startTime", activity.getStartTime());
		TIME_MAP.put("endTime", activity.getEndTime());
	}

	/**
	 * 判断List<Knowledge>的对象code是否有重复，有重复true
	 *
	 * @param list
	 * @return
	 */
	private Boolean knowledgeIsRepeat(List<MemberDto> list) {
		Set<MemberDto> set = new TreeSet<MemberDto>(new Comparator<MemberDto>() {
			public int compare(MemberDto a, MemberDto b) {
				if(a.getAccountId() == null || b.getAccountId() == null){
					return 1;
				}
				// 字符串则按照asicc码升序排列
				return a.getAccountId().compareTo(b.getAccountId());
			}
		});
		set.addAll(list);
		if (set.size() < list.size()) {
			return true;
		}
		return false;
	}

	private List<MemberDto> checkParams(MatchDto matchDto, Integer type){
		Activity activity = activityService.getActivity(ACTIVITY_ID);
		LocalDate endApplyDate = DateUtil.stringToLocalDate(activity.getProperty1());
		if(LocalDate.now().isAfter(endApplyDate)){
			throw new ServiceException("报名时间已截止");
		}
		String name = matchDto.getName();
		String userId = matchDto.getUserId();
		List<MemberDto> memberList = matchDto.getMemberList();
		if(StringUtils.isBlank(name)){
			throw new ServiceException("战队名不能为空");
		}
		if(CollectionUtils.isEmpty(memberList)){
			throw new ServiceException("队员不能为空");
		}
		Iterator<MemberDto> iterator = memberList.iterator();
		while (iterator.hasNext()){
			MemberDto next = iterator.next();
			if(next.getAccountId() == null){
				iterator.remove();
			}
		}
		//校验人数
		List<MemberDto> leaderList = memberList.stream().filter(t -> "leader".equals(t.getRole())).collect(Collectors.toList());
		if(leaderList.size() != 1){
			throw new ServiceException(-2, "资料未填写完整或资料有误！");
		}
		//
		List<MemberDto> normalList = memberList.stream().filter(t -> "normal".equals(t.getRole())).collect(Collectors.toList());
		if(normalList.size() != 4){
			throw new ServiceException(-2, "资料未填写完整或资料有误！");
		}
		if(knowledgeIsRepeat(memberList)){
			throw new ServiceException("请勿重复添加参赛人员");
		}
		//队员
		for (MemberDto memberDto : memberList) {
			if(StringUtils.isBlank(memberDto.getQq())){
				throw new ServiceException("请填写QQ号");
			}
			User user = userService.getUserByAccountId(memberDto.getAccountId());
			if (user == null) {
				throw new ServiceException(-2, "用户" + memberDto.getAccountId() + "不存在");
			}
			if("leader".equals(memberDto.getRole()) && !userId.equals(user.getUserId())){
				throw new ServiceException("只有本队队长才能进行报名哦！");
			}
			LambdaQueryWrapper<ActivityTeamMember> wrapper = new LambdaQueryWrapper<>();
			wrapper.eq(ActivityTeamMember::getUserId, user.getUserId()).last("limit 1");
			ActivityTeamMember member = activityTeamMemberMapper.selectOne(wrapper);
			String str = "队员";
			if(MatchRoleEnum.LEADER.getValue().equals(memberDto.getRole())){
				str = "队长";
			}
			if (member != null) {
				throw new ServiceException(str + memberDto.getAccountId() + "已报名");
			}
			if(type == 0){
				int count = userSettingMapper.selectCount(new LambdaQueryWrapper<UserSetting>().eq(UserSetting::getUserId, user.getUserId()).eq(UserSetting::getHasCertification, 1));
				if (count <= 0) {
					memberDto.setIsReal(0);
				} else {
					memberDto.setIsReal(1);
				}
			} else {
				int count = userSettingMapper.selectCount(new LambdaQueryWrapper<UserSetting>().eq(UserSetting::getUserId, user.getUserId()).eq(UserSetting::getHasCertification, 1));
				if("aliyun".equals(env)){
					if (count <= 0) {
						throw new ServiceException(str + memberDto.getAccountId() + "未实名");
					}
				}

			}
			memberDto.setUserId(user.getUserId());
			memberDto.setAccountId(user.getAccountId());
			memberDto.setNickname(user.getNickname());
			memberDto.setAvatarUrl(StringUtils.isBlank(user.getAvatarUrl()) ? Constants.DEFAULT_AVATAR : user.getAvatarUrl());
		}
		return memberList;
	}

	@Override
	public Map<String, Object> confirm(MatchDto matchDto) {
		String name = matchDto.getName();
		List<MemberDto> memberList = checkParams(matchDto, 0);
		Map<String, Object> result = new HashMap<>();
		//队员
		Map<String, List<MemberDto>> map = memberList.stream().collect(Collectors.groupingBy(MemberDto::getRole));
		result.put("name", name);
		result.put("num", memberList.size() - 1);
		result.put("leader", map.get("leader").get(0));
		result.put("normalList", map.get("normal"));
		result.put("alternateList", map.get("alternate"));
		return result;
	}

	@Override
	public Map<String, List<MatchVo>> getApplyInfo(MatchDto matchDto) {
		String userId = matchDto.getUserId();
		LambdaQueryWrapper<ActivityTeamMember> wrapper = new LambdaQueryWrapper<>();
		wrapper.eq(ActivityTeamMember::getUserId, userId).last("limit 1");
		ActivityTeamMember member = activityTeamMemberMapper.selectOne(wrapper);
		if (member == null) {
			return null;
		}
		Integer teamId = member.getTeamId();
		List<MatchVo> list = activityTeamMapper.selectUserList(teamId);
		for (MatchVo matchVo : list) {
			if(StringUtils.isBlank(matchVo.getAvatarUrl())){
				matchVo.setAvatarUrl(Constants.DEFAULT_AVATAR);
			}
		}
		Map<String, List<MatchVo>> map = list.stream().collect(Collectors.groupingBy(MatchVo::getRole));
		ActivityTeam team = activityTeamMapper.selectById(teamId);
		map.get("leader").get(0).setTeamName(team.getTeamName());
		map.get("leader").get(0).setNum(list.size() - 1);
		return map;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void apply(MatchDto matchDto) {
		String name = matchDto.getName();
		String userId = matchDto.getUserId();
		List<MemberDto> memberList = checkParams(matchDto, 1);
		//队伍
		ActivityTeam team = new ActivityTeam();
		team.setActivityId(ACTIVITY_ID);
		team.setUserId(userId);
		team.setTeamName(name);
		activityTeamMapper.insert(team);
		//队员
		for (MemberDto memberDto : memberList) {
			ActivityTeamMember record = new ActivityTeamMember();
			record.setTeamId(team.getId());
			record.setUserId(memberDto.getUserId());
			record.setQq(memberDto.getQq());
			record.setRole(memberDto.getRole());
			record.setIsReal(1);
			activityTeamMemberMapper.insert(record);
		}
	}

	@Override
	public Object matchInfo(MatchDto matchDto) {
		String userId = matchDto.getUserId();
		Map<String, Object> result = new HashMap<>();
		LambdaQueryWrapper<ActivityTeamMember> wrapper = new LambdaQueryWrapper<>();
		wrapper.eq(ActivityTeamMember::getUserId, userId).eq(ActivityTeamMember::getStatus, 1).last("limit 1");
		Integer count = activityTeamMemberMapper.selectCount(wrapper);
		result.put("isApply", count > 0 ? 1 : 0);
		//场次;0=海选，1=四强，2=半决，3=总决
		Integer round = matchDto.getRound();
		if(round == null){
			throw new ServiceException("场次不能为空");
		}
		if(round == 0){
			Map<String, Object> map = new LinkedHashMap<>();
			List<MatchVo> matchList = activityTeamMapper.selectMatchList(round);
			if(CollectionUtils.isEmpty(matchList)){
				result.put("data", null);
			} else {
				LinkedHashMap<String, List<MatchVo>> dateMap = matchList.stream().collect(Collectors.groupingBy(MatchVo::getDate, LinkedHashMap::new, Collectors.toList()));
				for (String date : dateMap.keySet()) {
					List<MatchVo> matchVoList = dateMap.get(date);
					Map<String, List<MatchVo>> groupMap = matchVoList.stream().collect(Collectors.groupingBy(MatchVo::getGroupName, LinkedHashMap::new, Collectors.toList()));
					map.put(date, groupMap);
				}
				result.put("data", map);
			}
		} else if(round == 1){
			List<MatchVo> matchList = activityTeamMapper.selectMatchList(round);
			result.put("data", matchList);
		} else if(round == 2){
			List<MatchVo> matchList = activityTeamMapper.selectMatchList(round);
			if(CollectionUtils.isEmpty(matchList)){

			}
			result.put("data", matchList);
		} else{
			List<MatchVo> matchList = activityTeamMapper.selectMatchList(round);
			if(!CollectionUtils.isEmpty(matchList)){
				result.put("data", matchList.get(0));
			}
		}
		return result;
	}


	/**
	 * 【赛事奖励】
	 冠军：高级头像框＋座驾＋王者冠军标签
	 亚军：高级头像框 + 亚军标签
	 季军：高级头像框 + 季军标签
	 8强队伍： 八强标签
	 海选赛胜场队伍：基础头像框
	 * @param matchDto
	 */
	@Override
	public void givePrize(MatchDto matchDto) {
		Integer round = matchDto.getRound();
		String win = matchDto.getWin();
		Integer redTeamId = matchDto.getRedTeamId();
		Integer blueTeamId = matchDto.getBlueTeamId();
		Integer flag = matchDto.getFlag();
		Integer teamId = null;
		String pwd = matchDto.getPwd();
		if(!"8704".equals(pwd)){
			throw new ServiceException("密码错误");
		}
		if(round == null){
			throw new ServiceException("回合不能为空");
		}
		if(round != 0 && (win == null || win == "")){
			throw new ServiceException("结果不能为空");
		}
		if(round != 0 && (redTeamId == null || redTeamId == null)){
			throw new ServiceException("队伍id不能为空");
		}
		List<ActivityPrize> prizeList = activityService.getPrizeList(ACTIVITY_ID, null);
		//类型：0=基础头像框,1=高级头像框,2=座驾,10=冠军标签,11=亚军标签,12=季军标签,13=八强标签
		//场次;0=海选，1=四强，2=半决，3=总决
		if(round == 0){
		/*	LambdaQueryWrapper<ActivityMatch> matchWrapper = new LambdaQueryWrapper<>();
			matchWrapper.eq(ActivityMatch::getRound, 0).eq(ActivityMatch::getStatus, 1);
			List<ActivityMatch> matchList = activityMatchMapper.selectList(matchWrapper);*/
			if("red".equals(win)){
				teamId = redTeamId;
			} else {
				teamId = blueTeamId;
			}
			//0=基础头像框
			doGivePrize(round, ActivityPrizeEnum.MATCH_LOW_HEAD.getType(), teamId, prizeList);
		} else if(round == 2 && flag != null && flag == 1){
			if("red".equals(win)){
				teamId = redTeamId;
			} else {
				teamId = blueTeamId;
			}
			//1=高级头像框
			doGivePrize(round, ActivityPrizeEnum.MATCH_HEIGHT_HEAD.getType(), teamId, prizeList);
			//12=季军标签
			doGivePrize(round, ActivityPrizeEnum.MATCH_THIRD_LABEL.getType(), teamId, prizeList);

			//八强标签发放处理
			try {
				Thread.sleep(500);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			//过滤
			LambdaQueryWrapper<ActivityMatch> wrapper = new LambdaQueryWrapper<>();
			wrapper.in(ActivityMatch::getRound, 2).eq(ActivityMatch::getStatus, 1);
			List<ActivityMatch> matches = activityMatchMapper.selectList(wrapper);
			List<Integer> filterTeamIds = new LinkedList<>();
			for (ActivityMatch match : matches) {
				if("red".equals(match.getWin())){
					filterTeamIds.add(match.getRedTeamId());
				} else {
					filterTeamIds.add(match.getBlueTeamId());
				}
			}
			log.warn("methodName：过滤的队伍={}", JSON.toJSONString(filterTeamIds));
			//待发放队伍
			LambdaQueryWrapper<ActivityMatch> matchWrapper = new LambdaQueryWrapper<>();
			matchWrapper.eq(ActivityMatch::getRound, 1).eq(ActivityMatch::getStatus, 1);
			List<ActivityMatch> matchList = activityMatchMapper.selectList(matchWrapper);
			for (ActivityMatch match : matchList) {
				if(!filterTeamIds.contains(match.getRedTeamId())){
					//13=八强标签
					doGivePrize(round, ActivityPrizeEnum.MATCH_FOURTH_LABEL.getType(), match.getRedTeamId(), prizeList);
					log.warn("methodName：八强发放的队伍={}", JSON.toJSONString(match.getRedTeamId()));
				}
				if(!filterTeamIds.contains(match.getBlueTeamId())){
					//13=八强标签
					doGivePrize(round, ActivityPrizeEnum.MATCH_FOURTH_LABEL.getType(), match.getBlueTeamId(), prizeList);
					log.warn("methodName：八强发放的队伍={}", JSON.toJSONString(match.getRedTeamId()));
				}
			}
		} else if(round == 3){
			if("red".equals(win)){
				//1=高级头像框
				doGivePrize(round, ActivityPrizeEnum.MATCH_HEIGHT_HEAD.getType(), redTeamId, prizeList);
				//2=座驾
				doGivePrize(round, ActivityPrizeEnum.MATCH_CAR.getType(), redTeamId, prizeList);
				//10=冠军标签
				doGivePrize(round, ActivityPrizeEnum.MATCH_FIRST_LABEL.getType(), redTeamId, prizeList);

				//1=高级头像框
				doGivePrize(round, ActivityPrizeEnum.MATCH_HEIGHT_HEAD.getType(), blueTeamId, prizeList);
				//11=亚军标签
				doGivePrize(round, ActivityPrizeEnum.MATCH_SECOND_LABEL.getType(), blueTeamId, prizeList);
			} else {
				//1=高级头像框
				doGivePrize(round, ActivityPrizeEnum.MATCH_HEIGHT_HEAD.getType(), blueTeamId, prizeList);
				//2=座驾
				doGivePrize(round, ActivityPrizeEnum.MATCH_CAR.getType(), blueTeamId, prizeList);
				//10=冠军标签
				doGivePrize(round, ActivityPrizeEnum.MATCH_FIRST_LABEL.getType(), blueTeamId, prizeList);

				//1=高级头像框
				doGivePrize(round, ActivityPrizeEnum.MATCH_HEIGHT_HEAD.getType(), blueTeamId, prizeList);
				//11=亚军标签
				doGivePrize(round, ActivityPrizeEnum.MATCH_SECOND_LABEL.getType(), blueTeamId, prizeList);
			}
		}
	}

	//发放奖励
	private void doGivePrize(Integer round, Integer type, Integer teamId, List<ActivityPrize> prizeList){
		LambdaQueryWrapper<ActivityTeamMember> wrapper = new LambdaQueryWrapper<>();
		wrapper.eq(ActivityTeamMember::getTeamId, teamId);
		List<ActivityTeamMember> list = activityTeamMemberMapper.selectList(wrapper);
		for (ActivityTeamMember member : list) {
			//是否已经领取
			String key = RedisConstans.putRediskey(RedisConstans.ACTIVITY_MATCH_PRIZE, ACTIVITY_ID, round, type, member.getUserId());
			if(redisUtil.get(key) != null){
				//continue; todo
			}
			ActivityPrize prize = prizeList.stream().filter(p -> p.getType().equals(type)).collect(Collectors.toList()).get(0);
			savePrize(prize, member.getUserId());
			redisUtil.set(key, "1", RedisConstans.TWO_MONTH);
		}
	}

	@Override
	public void savePrize(ActivityPrize prize, String userId){
		/*String key = RedisConstans.putRediskey(RedisConstans.ACTIVITY_PRIZE_RECORD, ACTIVITY_ID, prize.getType(), userId);
		if(redisUtil.get(key) != null){
			return;
		}*/
		if(prize.getSource() == 2){
			giftService.saveUserDress(ACTIVITY_ID, userId, prize.getGiftId(), 31, 1, "王者争霸赛获得");
		} else {
			giftService.savePrize(ACTIVITY_ID, userId, prize.getGiftId(), 30, 1);
		}
		//redisUtil.set(key, 1, RedisConstans.ONE_MONTH);
	}
}
